<!--
 * @FilePath: \vue-typescript-admin-template\src\views\table\complex-table.vue
 * @Author: maskMan
 * @Date: 2023-04-09 20:16:27
 * @LastEditTime: 2024-06-12 11:56:08
 * @Reference: 引用方
 * @Descripttion: 说明 游戏
-->
<template>
  <div class="app-container">
    <!-- 标题输入框 -->
    <div class="filter-container">
      <!-- 添加 -->
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t('table.add') }}
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <!-- 表格头ID -->
      <el-table-column
        :label="$t('table.id')"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <!-- 用户账号 -->
      <el-table-column label="游戏id" width="180px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.gameId }}</span>
        </template>
      </el-table-column>
      <!-- 游戏名字-->
      <el-table-column label="游戏名字" width="180px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.gameName }}</span>
        </template>
      </el-table-column>
      <!-- 游戏图标 -->
      <el-table-column label="图标地址" width="180px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.image }}</span>
        </template>
      </el-table-column>
      <!-- 游戏说明 -->
      <el-table-column label="游戏说明" width="380px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.desc }}</span>
        </template>
      </el-table-column>
      <!-- 表格操作 -->
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="230"
        class-name="fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('table.modify') }}
          </el-button>
          <!-- <el-button
            v-if="row.status !== 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            {{ $t('table.delete') }}
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 弹出编辑操作面板 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="tempArticleData"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <!-- 游戏ID -->
        <el-form-item label="游戏id" prop="gameId">
          <el-input
            v-model="tempArticleData.gameId"
            placeholder="请输入游戏id"
          />
        </el-form-item>
        <!-- 游戏名字 -->
        <el-form-item label="游戏名字" prop="gameName">
          <el-input
            v-model="tempArticleData.gameName"
            placeholder="请输入游戏名字"
          />
        </el-form-item>
        <!-- 游戏图标 -->
        <el-form-item label="游戏图标">
          <el-input
            v-model="tempArticleData.image"
            placeholder="请输入游戏图标地址"
          />
        </el-form-item>
        <!-- 游戏说明 -->
        <el-form-item label="说明">
          <el-input
            v-model="tempArticleData.desc"
            :autosize="{ minRows: 10, maxRows: 30 }"
            type="textarea"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <!-- 创建和更新数据按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 获取阅读数详情预览 -->
    <el-dialog
      :visible.sync="dialogPageviewsVisible"
      title="Reading statistics"
    >
      <el-table
        :data="pageviewsData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pageviews" label="Pageviews" />
      </el-table>
      <!-- 关闭按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPageviewsVisible = false">{{
          $t('table.confirm')
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { Form } from 'element-ui'
import { cloneDeep } from 'lodash'
import {
  getArticles,
  getPageviews,
  createArticle,
  updateArticle,
  defaultGameData,
getGameList
} from '@/api/articles'
import { IArticleData, IGameInfo } from '@/api/types'
import { exportJson2Excel } from '@/utils/excel'
import { formatJson } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'
import { createGame, updateGame } from '@/api/users'
const calendarTypeOptions = [
  { key: 'CN', displayName: 'China' },
  { key: 'US', displayName: 'USA' },
  { key: 'JP', displayName: 'Japan' },
  { key: 'EU', displayName: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce(
  (acc: { [key: string]: string }, cur) => {
    acc[cur.key] = cur.displayName
    return acc
  },
  {}
) as { [key: string]: string }

@Component({
  name: 'ComplexTableGame',
  components: {
    Pagination
  },
  filters: {
    typeFilter: (type: string) => {
      return calendarTypeKeyValue[type]
    }
  }
})
export default class extends Vue {
vLoading(vLoading: any) {
throw new Error('Method not implemented.')
}
$index(row: any, $index: any) {
throw new Error('Method not implemented.')
}
vShow(vShow: any) {
throw new Error('Method not implemented.')
}
  private tableKey = 0
  private list: any[] = []
  private total = 0
  private listLoading = true
  private listQuery = {
    page: 1,
    limit: 20,
    gameId: '',
    sort: '+id'
  }

  private importanceOptions = [1, 2, 3]
  private calendarTypeOptions = calendarTypeOptions
  private sortOptions = [
    { label: 'ID Ascending', key: '+id' },
    { label: 'ID Descending', key: '-id' }
  ]

  private statusOptions = ['一级会员', '二级会员', '三级会员']
  private showReviewer = false
  private dialogFormVisible = false
  private dialogStatus = ''
  private textMap = {
    update: 'Edit',
    create: 'Create'
  }

  private dialogPageviewsVisible = false
  private pageviewsData = []
  // 编辑数据验证
  private rules = {
    gameId: [{ required: true, message: '游戏ID不能为空', trigger: 'blur' }],
    gameName: [{ required: true, message: '游戏名字不能为空', trigger: 'blur' }]
  }

  private downloadLoading = false
  private tempArticleData = defaultGameData
row: any

  created() {
    this.getList()
  }

  // 获取文章数据源
  private async getList() {
    this.listLoading = true
    const data:any  = await getGameList(this.listQuery)
    if(data){
      this.list = data.items
      this.total = data.total
    }
    // Just to simulate the time of the request
    setTimeout(() => {
      this.listLoading = false
    }, 0.5 * 1000)
  }

  private handleFilter() {
    this.listQuery.page = 1
    this.getList()
  }

  private handleModifyStatus(row: any, status: string) {
    this.$message({
      message: '操作成功',
      type: 'success'
    })
    row.status = status
  }

  private sortChange(data: any) {
    const { prop, order } = data
    if (prop === 'id') {
      this.sortByID(order)
    }
  }

  private sortByID(order: string) {
    if (order === 'ascending') {
      this.listQuery.sort = '+id'
    } else {
      this.listQuery.sort = '-id'
    }
    this.handleFilter()
  }

  private getSortClass(key: string) {
    const sort = this.listQuery.sort
    return sort === `+${key}` ? 'ascending' : 'descending'
  }

  private resetTempArticleData() {
    this.tempArticleData = cloneDeep(defaultGameData)
  }

  private handleCreate() {
    this.resetTempArticleData()
    this.dialogStatus = 'create'
    this.dialogFormVisible = true
    this.$nextTick(() => {
      const tem = this.$refs.dataForm as Form
      tem.clearValidate()
    })
  }

  private createData() {
    const tem = this.$refs.dataForm as Form
    tem.validate(async (valid) => {
      if (valid) {
        const articleData = this.tempArticleData
        const  data  = await createGame(articleData)
        if(data){
          this.list.unshift(data)
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
          return
        }
        this.$notify({
            title: '失败',
            message: '创建失败',
            type: "error",
            duration: 2000
          })
      }
    })
  }

  private handleUpdate(row: any) {
    this.tempArticleData = Object.assign({}, row)
    // this.tempArticleData.timestamp = +new Date(this.tempArticleData.timestamp)
    this.dialogStatus = 'update'
    this.dialogFormVisible = true
    this.$nextTick(() => {
      const tem = this.$refs.dataForm as Form
      tem.clearValidate()
    })
  }

  private updateData() {
    const tem = this.$refs.dataForm as Form
    tem.validate(async (valid) => {
      if (valid) {
        const tempData = Object.assign({}, this.tempArticleData)
        const  data:any = await updateGame(tempData)
        if(data){
          const index = this.list.findIndex((v) => v.gameId === tempData['gameId'])
          if(index>=0){
            this.list.splice(index, 1, tempData)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            return
          }
        }
        this.$notify({ title: '更新用户', message: '更新失败',type: "error",duration: 2000})
      }
    })
  }
  private handleDelete(row: any, index: number) {
    this.$notify({
      title: 'Success',
      message: 'Delete Successfully',
      type: 'success',
      duration: 2000
    })
    this.list.splice(index, 1)
  }
  private async handleGetPageviews(pageviews: string) {
    const { data } = await getPageviews({ pageviews })
    this.pageviewsData = data.pageviews
    this.dialogPageviewsVisible = true
  }
  private handleDownload() {
    this.downloadLoading = true
    const tHeader = ['account', 'createTime', 'endTime', 'commit', 'status']
    const filterVal = ['account', 'createTime', 'endTime', 'commit', 'status']
    const data = formatJson(filterVal, this.list)
    exportJson2Excel(tHeader, data, 'table-list')
    this.downloadLoading = false
  }
  private formaDate = function (
    type?: 1 | 2 | 3 | 4 | 5 | 6 | 7,
    data?: Date | string | number
  ) {
    var dd = data ? new Date(data) : new Date()
    const y: any = dd.getFullYear() //年
    let m: any = dd.getMonth() + 1 //月
    m = m < 10 ? '0' + m : m
    let d: any = dd.getDate() //日
    d = d < 10 ? '0' + d : d
    let h: any = dd.getHours() //时
    h = h < 10 ? '0' + h : h
    let i: any = dd.getMinutes() //分
    i = i < 10 ? '0' + i : i
    let s: any = dd.getSeconds() //秒
    s = s < 10 ? '0' + s : s
    if (type == 1) {
      return y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s
    } else if (type == 2) {
      return y + '-' + m + ' ' + d + ' ' + h + ':' + i
    } else if (type == 3) {
      return h + ':' + i + ':' + s
    } else if (type == 4) {
      return m + '-' + d + ' ' + h + ':' + i + ':' + s
    } else if (type == 5) {
      return y.toString() + m.toString() + d.toString()
    } else if (type == 6) {
      return (
        y.toString() +
        m.toString() +
        d.toString() +
        h.toString() +
        i.toString() +
        s.toString()
      )
    } else if (type == 7) {
      return m.toString() + '月' + d.toString() + '日' + h.toString() + '时'
    }
  }
}
</script>
